﻿package com.wly.event
{
	import flash.utils.Dictionary;

	public class EventManager
	{
		private var _eventPool:Dictionary;
		static private var _instance:EventManager;
		
		public function EventManager()
		{
			_instance = this;
			_eventPool = new Dictionary();
		}
		
		static public function getInstance():EventManager
		{
			if(!_instance)
			{
				_instance = new EventManager();
			}
			return _instance;
		}
		
		public function registerEvent(eventId:int, callbackFunc:Function):void
		{
			var eventCallBackItem:EventCallback = new EventCallback();
			eventCallBackItem.func              = callbackFunc;
			eventCallBackItem.eventId           = eventId;
			
			var eventCallbackArr:Array          = _eventPool[eventCallBackItem.eventId] as Array;
			if(eventCallbackArr)
			{
				var i:int;
				for(i=0; i<eventCallbackArr.length; i++)
				{
					var eventCallBackItemTmp:EventCallback = eventCallbackArr[i] as EventCallback;
					if(eventCallBackItemTmp && eventCallBackItemTmp.func==eventCallBackItem.func)
					{
						return;
					}
				}
				
				eventCallbackArr.push(eventCallBackItem);
				return;
			}
			else
			{
				eventCallbackArr = [];
				eventCallbackArr.push(eventCallBackItem);
				_eventPool[eventCallBackItem.eventId] = eventCallbackArr;
			}
		}
		
		public function unRegisterEvent(eventId:int, callbackFunc:Function):void
		{
			var eventCallbackArr:Array          = _eventPool[eventId] as Array;
			if(!eventCallbackArr)
			{
				return;
			}
			
			var eventCallBackItem:EventCallback;
			var i:int;
			for(i=0; i<eventCallbackArr.length; i++)
			{
				eventCallBackItem = eventCallbackArr[i] as EventCallback;
				if(eventCallBackItem && eventCallBackItem.func==callbackFunc)
				{
					eventCallbackArr.splice(i,1);
					break;
				}
			}
			
			if(!eventCallbackArr.length)
			{
				delete _eventPool[eventId];
			}
		}
		
		public function dispatchEvent(eventId:int, param:*):void
		{
			var eventCallbackArr:Array          = _eventPool[eventId] as Array;
			if(!eventCallbackArr)
			{
				return;
			}
			
			var eventCallBackItem:EventCallback;
			var i:int;
			for(i=0; i<eventCallbackArr.length; i++)
			{
				eventCallBackItem = eventCallbackArr[i] as EventCallback;
				if(eventCallBackItem)
				{
					eventCallBackItem.func(param);
				}
			}
			
		}
	}
}